from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods

from . import models


# Create your views here.

def login(request):
    print("login")
    return HttpResponse("weblogin")


POST_FORM = '''
<form method='post' action='/test_get_post/'>
    用户名：<input type='text' name='uname'>
    <input type='submit' value='提交'>
</form>
'''


@require_http_methods(["GET"])
def main_page(request):
    html = """
    <h4>这是我的网站首页</h4>
    <a href="http://www.datutusuibi.com/" target="_blank">大土土随笔</a>
    """
    return HttpResponse(html)


@require_http_methods(["GET"])
def add_book_example(request):
    response = {}
    try:
        # book = Book(book_name=request.GET.get('book_name'))
        # book.save()
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1

    return JsonResponse(response)


@csrf_exempt
def test_get_post(request):
    if request.method == 'GET':
        print(request.GET)
        # print(request.GET['m'])
        # print(request.GET.getlist('m'))
        # print(request.GET.get('t', 'no t'))
        return HttpResponse('test get  ok')
    elif request.method == 'POST':
        # 处理用户提交数据
        print('uname is : ', request.POST['uname'])
        return HttpResponse('test post ok')
    else:
        pass

    return HttpResponseRedirect('/main_page/')


def test_get_post_example(request):
    print('path info is : ', request.path_info)
    print('method is : ', request.method)
    print('querystring is : ', request.GET)
    print('full path is :', request.get_full_path())
    print('客户端IP is :', request.META['REMOTE_ADDR'])

    if request.method == 'GET':
        print("GET REQUEST")
        request.GET['参数名']  # QueryDict
        request.GET.get('参数名', '默认值')
        request.GET.getlist('参数名')
        # mypage?a=100&b=200&c=300&b=400
        #  request.GET=QueryDict({a:['100'],b:['200','400'],c:['300']})
        #  request.GET['a']
        #  request.GET['b'] # Error
    elif request.method == 'POST':
        request.POST['参数名']  # QueryDict
        request.POST.get('参数名', '默认值')
        request.POST.getlist('参数名')
        # mypage?a=100&b=200&c=300&b=400
        #  request.GET=QueryDict({a:['100'],b:['200','400'],c:['300']})
        #  request.GET['a']
        #  request.GET['b'] # Error
        print("POST REQUEST")
    else:
        pass
        print("Others REQUEST")

    return HttpResponse('test request ok')
